/**
 * 从localstorage中获取数据
 * @param key key字符串
 * @returns key对应值的对象或数组
 *
 */
export const getKvLS = <T>(key: string): T | undefined | null | string => {
    try {
        let val = localStorage.getItem(key);
        val = JSON.parse(val);
        return val;
    } catch (e) {
        console.log(e.message);
        return null;
    }
};

/**
 * 单次将数据存入localstorage中
 * @param key 要创建或更新的key
 * @param value 要创建或更新的key对应的值
 */
export const setKvLS = <T>(key: string, value: T): void => {
    try {
        const val = JSON.stringify(value);
        localStorage.setItem(key, val);
    } catch (e) {
        console.log(e.message);
    }
};

/**
 * 批量将数据存入localStorage,以对象key作为存储key
 * @param data 对象
 */
export const saveDataToLocalLS = <T>(data: T): void => {
    try {
        const keys = Object.keys(data);
        for (const key of keys) {
            setKvLS(key, data[key]);
        }
    } catch (e) {
        console.log(e.message);
    }
};

/**
 * 从sessionStorage中获取数据
 * @param key key字符串
 * @returns key对应值的对象或数组
 */
export function getKvSS<T>(key: string): T | undefined | null | string {
    try {
        let val = sessionStorage.getItem(key);
        val = JSON.parse(val);
        return val;
    } catch (e) {
        console.log(e.message);
        return null;
    }
}

/**
 * 单次将数据存入sessionStorage中
 * @param key 要创建或更新的key
 * @param value 要创建或更新的key对应的值
 */
export const setKvSS = <T>(key: string, value: T): void => {
    try {
        const val = JSON.stringify(value);
        sessionStorage.setItem(key, val);
    } catch (e) {
        console.log(e.message);
    }
};

/**
 * 批量将数据存入sessionStorage,以对象key作为存储key
 * @param data 对象
 */
export const saveDataToLocalSS = <T>(data: T): void => {
    try {
        const keys = Object.keys(data);
        for (const key of keys) {
            setKvSS(key, data[key]);
        }
    } catch (e) {
        console.log(e.message);
    }
};

export interface UtilStruct {
    getKvLS: (key: string) => string;
    setKvLS: (key: string, value) => void;
    getKvSS: (key: string) => string;
    setKvSS: (key: string, value) => void;
    saveDataToLocalLS: (key: string, value) => void;
    saveDataToLocalSS: (key: string, value) => void;
}
